package zuo.from0516.basic2020.class01;

import java.util.Arrays;

public class Code01_SelectionSort {
    public static void selectionSort(int[] nums){
        if(nums == null || nums.length <2){
            return;
        }
        for (int i = 0; i < nums.length-1; i++) {
            int minIndex = i;
            for (int j = i+1; j < nums.length; j++) {
                if(nums[minIndex]>nums[j]){
                    minIndex = j;
                }
            }
            swap(nums, i ,minIndex);
        }
    }

    public static void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public static void comparator(int[] nums){
        Arrays.sort(nums);
    }

    public static int[] generateRandomArray(int maxSize, int maxValue){
        int[] arr = new int[(int)((maxSize + 1) * Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int)((maxValue +1)*Math.random()) - (int)((maxValue)*Math.random());
        }
        return arr;
    }

    public static int[] copyArr(int[] arr){
        if(arr == null){
            return null;
        }
        int[] copy = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            copy[i] = arr[i];
        }
        return copy;
    }

    public static boolean isEqual(int[] arr1,int[] arr2){
        if(arr1.length != arr2.length){
            return false;
        }
        if(arr1 == null ^ arr2 == null){
            return false;
        }
        if(arr1 == null && arr2 == null){
            return true;
        }
        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i] != arr2[i]){
                return false;
            }
        }
        return true;
    }

    public static void printArr(int[] arr){
        if(arr.length == 0){
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
//        System.out.println();
    }

    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 5;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = generateRandomArray(maxSize, maxValue);
            int[] arr2 = copyArr(arr1);
            printArr(arr1);
            printArr(arr2);
            selectionSort(arr1);
            comparator(arr2);
            if(!isEqual(arr1,arr2)){
                succeed = false;
                printArr(arr1);
                printArr(arr2);
                System.out.println(succeed);
                break;
            }
        }
        System.out.println(succeed?"successed!" : "failed……");
    }
}
